var topicModel = require('../models/topicModel');
var cateModel = require('../models/cateModel');
var userModel = require('../models/userModel');
var replyModel = require('../models/replyModel');
var countTimeAgo = require('../config/countTimeAgo');
//加载eventproxy模块
var eventproxy = require('eventproxy');
var index = {};

//错误-页面
function showError(req,res,title,errStr){
    res.render('./common/error',{
        tempName:'error',
        title: title,
        err: errStr
    });
}

//创建话题-页面
index.create = function (req,res) {
    //查询话题分类
    cateModel.find({},{},{
        //此处写排序或者分页操作
        sort:{
            ordernumber:1
        }
    },function(err,data){
        //console.log(data);
        res.render('./topic/createTopic',{tempName:'createTopic',typeList:data});
    });
    
};

//创建话题(数据)
index.doCreate = function (req,res) {    
    //console.log(req.body);
    var data = req.body;
    var newTopic = {
        title: data.title,
        content: data.content,
        topicType: data.type,
        poster: req.session.user._id
    };
    //console.log(newTopic);
    //创建话题
    topicModel.create(newTopic,function(err,msg){
        //console.log(msg);
        //用户加积分
        var con = {_id:req.session.user._id};
        userModel.update(con,{$inc: {score: 5}},function(err,msg2){
            //console.log(err);
            if(!err){
                //更新session中用户的积分
                req.session.user.score += 5;
                //跳转到刚生成的话题帖页面
                //console.log(msg);
                res.redirect('/topics/'+msg._id);
                //res.render('./common/info',{info:'Topic posted successfully!',tempName:'info',title:"Topic posted"});
            }
        });
    });
    
};

//跳转到相应话题页面(根据话题id) 该方法未写好 废弃
/* index.goTopic = function (req,res) {
    //console.log("topic id: "+req.params._id);
    //关联查询 关联话题类型和发布者 使用populate方法, 其中字段为topicModel中相应字段名, 则mongoose会自动去相应model里相应字段定义的关联模型去查找相应ObjectId的值, 例如此处话题类型topicType关联的模型是cate, 发布者poster关联的模型是user

    

    topicModel.findOne({_id:req.params._id}).populate('topicType',{catename:1}).populate('poster').exec(function(err,data){
        if(!err || data !== null || data !== undefined){
            //每浏览一次增加访问次数一次
            topicModel.update({_id:req.params._id},{$inc: {viewCount: 1}},function (err,msg) {

                //获取作者其他的话题
                var con = {
                    poster: data.poster._id,
                    //非当前话题(与当前查看的话题的id不一样)
                    _id: {
                        $ne: req.params._id
                    }
                };
                topicModel.find(con,{title:1,_id:1},{
                    sort:{createTime:1},    //按照发布时间从晚到早
                    limit: 5    //查询5条
                },function (err,data2) {
                    console.log(data2);
                    
                    res.render('./topic/topic',{topic:data,tempName:'topic',hisTopics:data2});
                });

                
            });
            
        }else{
            showError(req,res,'Error','The topic you want to view is deleted or blocked.');
        }
    });
}; */

//使用eventproxy进行处理的方法
//访问某个主题
index.goTopic = function (req,res) {
    var ep = new eventproxy();
    //用于查询该作者非当前帖子的其他帖子
    var con = {};
    ep.all('topicDetail','updateViews','noReplyData','topicRepliesList',function(returnData,updateResult,noReplyData,topicRepliesList){

        if(returnData === null || returnData === undefined){
            showError(req,res,'Error','The topic you want to view is deleted or blocked.');
        }else{
            res.render('./topic/topic',{
                tempName:'topic',
                topic: returnData.topicDetail,
                hisTopics: returnData.other5Topics,
                noReplyData: noReplyData,
                topicRepliesList: topicRepliesList
            });
        }
        
    });

    //获取该话题的细节
    topicModel.findOne({_id:req.params._id}).populate('topicType',{catename:1}).populate('poster').exec(function(err,topicDetail){
        //即goTopic中最开始定义的con
        
        if(undefined  === topicDetail || null === topicDetail){
            ep.emit('topicDetail',undefined);
        }else{
            con = {
                poster: topicDetail.poster._id,
                //非当前话题(与当前查看的话题的id不一样)
                _id: {
                    $ne: req.params._id
                }
            };

            //获取该话题作者的其他5条话题
            topicModel.find(con,{title:1,_id:1},{
                sort:{createTime:1},    //按照发布时间从晚到早
                limit: 5    //查询5条
            },function (err,other5Topics) {
                var returnData = {
                    topicDetail: topicDetail,
                    other5Topics: other5Topics
                }
                ep.emit('topicDetail',returnData);
            });

            //获取该话题的所有回复的列表
            replyModel.find({topic:req.params._id}).populate('user').exec(function(err,replyData){
                if(replyData.length == 0){
                    ep.emit('topicRepliesList',undefined);
                }else{
                    ep.emit('topicRepliesList',replyData);
                }
            });
            
        }
    });

    //该话题访问量+1
    topicModel.update({_id:req.params._id},{$inc: {viewCount: 1}},function (err,updateResult) {
        ep.emit('updateViews',updateResult);
    });

    //查询0回复量的话题的条件
    var noRepCon = {
        reply: {$size: 0}
    }
    
    //查询0回复量的话题
    topicModel.find(noRepCon,{title:1},{
        sort: {createTime:-1},
        limit: 5
    },function(err,noReplyData){
        //console.log(noReplyData);
        ep.emit("noReplyData",noReplyData);
    });
};

//发表话题回复
index.replyTopic = function(req,res){
    //var topicId = req.body.topicId
    //consoleconsole.log(req.body);
    

    //先获取当前的话题所有回复的数量, 用来确定新回复的楼层应该是多少
    var con ={_id: req.body.topicId};
    topicModel.findOne(con,{reply:1},function(err,thisTopic){
        //然后, 新建回复对象
        var reply = {
            content: req.body.content,
            user: req.session.user._id,
            topic: req.body.topicId,
            stair: (thisTopic.reply.length+1)
        }
        //创建reply对象
        replyModel.create(reply,function(err,replyData){
            //将reply对象加入到该话题中的回复列表中
            topicModel.update(con,{$push:{reply:replyData._id}},function(err,msg){
                //console.log(msg);
                
                //用户回复话题 则用户本身积分+2
                userModel.findOne({_id: req.session.user._id},function(err,userData){
                    if(userData){
                        userModel.update({_id: req.session.user._id},{$inc: {score: 2}},function(err,msg){
                            //console.log(err);
                            //console.log(msg);
                            res.redirect('/topics/'+req.body.topicId);
                        })
                    }
                })
            });
        });
    });
};

//对话题进行收藏的操作
index.collectTopic = function(req,res){
    if(req.session.user){
        if(req.query.topic){
            var con = {
                _id: req.session.user._id
            }
            if(req.params.opt === 'add'){
                userModel.update(con,{$push:{collections:req.query.topic}},function(err,msg){
                    req.session.user.collections.push(req.query.topic);
                    res.redirect('back');
                });
            }else{
                userModel.update(con,{$pull:{collections:req.query.topic}},function(err,msg){
                    
                    //console.log(req.session.user.collections);
                    var idx = req.session.user.collections.indexOf(req.query.topic);
                    req.session.user.collections.splice(idx,1);
                    res.redirect('back');
                });
            }
        }
    }else{
        res.render('login',{tempName:'login'});
    }
};

//给回复点赞
index.pretReply = function(req,res){
    var userId = req.session.user._id;
    var con = {_id:req.body.replyId};
    replyModel.findOne(con,function(err1,data1){
        if(err1){
            console.log(err1);
        }else{
            if(data1.likes.indexOf(userId+"") === -1){
                replyModel.update(con,{$push:{likes:userId}},function(err2,data2){
                    if(err2){
                        console.log(err2);
                        res.send("err");
                    }else{
                        replyModel.findOne(con,function(err3,data3){
                            res.send("{count:"+data3.likes.length+",flag:true}");
                        });
                    }
                });
                
            }else{
                replyModel.update(con,{$pull:{likes:userId}},function(err2,data2){
                    if(err2){
                        console.log(err2);
                        res.send("err");
                    }else{
                        replyModel.findOne(con,function(err3,data3){
                            res.send("{count:"+data3.likes.length+",flag:false}");
                        });
                    }
                });
            }
        }
    });
};

//修改话题
index.editTopic = function (req,res) {
    var ep = new eventproxy();
    var con = {_id: req.params._id};

    ep.all('cateList','topic',function(cateList,topic){
        if(req.session.user){
            if(req.session.user.level === 1 || topic.poster._id+"" === req.session.user._id){
                if(undefined  === topic){
                    showError(req,res,'Error','The topic you are about to edit is deleted or blocked.');
                }else{
                    //跳转至话题修改页面
                    res.render("/topic/editTopic",{temperName:"topic",topic:topic,cateList:cateList});
                }
            }
        }else{
            redirect("/login");
        }
    });

    //查询话题分类
    cateModel.find({},{},{
        //此处写排序或者分页操作
        sort:{
            ordernumber:1
        }
    },function(err,data){
        //console.log(data);
        ep.emit('cateList',data);
    });

    topicModel.findOne(con,function(err,topic){
        if(err){
            console.log(err);
        }else{
            ep.emit('topic',topic);
        }
    })
};

module.exports = index;